<template>
  <div id="chat-person">
    <van-sticky>
      <van-nav-bar :title="toUser?.username"  left-arrow @click-left="leftClick" @click-right="rightClick" style="background-color:#f6f7f9;">
        <!-- <template #right>
          <van-icon name="ellipsis" size="18" />
        </template> -->
      </van-nav-bar>
    </van-sticky>
    <div class="message" ref="divRef">
      <div class="private-chat">
        <div v-for="item in messages" :key="item.id">
          <div class="main" v-if="currentUser.id !== item.uid && item.uid === toUser?.id">
            <van-image
                round
                width="2.5rem"
                height="2.5rem"
                fit="cover"
                :src="toUser?.avatarUrl"
              />
            <div class="text">{{item.text}}</div>
          </div>

          <div class="selfMain" v-else-if="currentUser.id === item.uid && item.toId === toUser?.id ">
            <div class="selfText">{{item.text}}</div>
              <van-image
                class="selfImage"
                round
                width="2.5rem"
                height="2.5rem"
                fit="cover"
                :src="currentUser.avatarUrl"
              />
          </div>
        </div>
      </div>
      <div class="group-chat">
      </div>
    </div>
    <div class="userText">
      <van-cell-group inset>
        <van-field
          v-model="text"
          rows="1"
          autosize
          type="textarea"
          placeholder="请输入聊天内容...."
        >
          <template #button>
            <van-button 
              class="submit"
              size="small" 
              color="#3286A0 "
              plain
              @click="send"
            >
              发送
            </van-button>
          </template>
        </van-field>
      </van-cell-group>
    </div>
  </div>
</template>

<script setup lang="ts">
import { findAllInitUsingGET } from '../../api/imController';
import {useAppStoreWithOut} from '../../store/modules/app';
import { useCache } from '../../hooks/useCache';
import {getCurrentUser} from "../../services/user.ts";
import {ref, reactive, onMounted, nextTick} from 'vue';
import { useRouter } from 'vue-router';
import { showToast } from 'vant';

//定义消息的类型
interface ImMessage {
  uid: number;
  toId: number;
  text: any;
  username: any;
  avatarUrl: string;
  toAvatarUrl: string;
  profile: string;
}

const messages = ref<API.Im[]>([]);
const appStore = useAppStoreWithOut();
const {wsCache} = useCache();
const text = ref('')  // 聊天输入的内容
const toUser = ref<API.User>()  // 聊天对象
const divRef = ref()   // 聊天框的引用
const currentUser = ref();
const limitMessage = ref(10);

const router = useRouter();
const leftClick = () => {
  router.back();
}
const rightClick = () => {
  router.push({
    path: '/chatMessages',
  })
}

// todo页面滚动到最新位置的函数,未实现效果
const scrollBottom = () => {
  nextTick(() => {   // 等到页面元素出来之后再去滚动
    divRef.value.scrollTop = 500;
  })
}

// 页面加载完成触发此函数
onMounted(() => {
  toUser.value = wsCache.get(appStore.getCurrentSessionToUser);
  getHistoryMessage();
  scrollBottom();
})

//获取历史消息
const getHistoryMessage = () => {
  findAllInitUsingGET({
    limit: limitMessage.value
  }).then(res => {
    // console.log(res.data)
    messages.value = res.data
    limitMessage.value += 10;
  });
}


//获取当前登录用户的信息
currentUser.value = wsCache.get(appStore.getUserInfo);

console.log('currentUser.value:', currentUser.value.id);
// 建立 websocket 连接

// const client = new WebSocket(`ws://127.0.0.1:8088/ws?id=${currentUser.value.id}`)
const client = new WebSocket(`ws://8.134.92.187:8088/ws?id=${currentUser.value.id}`)
// const baseURL = import.meta.env.MODE === 'production' ? 'ws://8.134.92.187:8088/ws' : 'ws://127.0.0.1:8088/ws';
// const client = new WebSocket(`${baseURL}?id=${currentUser.value.id}`);

console.log('client:', client);
 
// const client = new WebSocket(`ws://pm-backend.dengxian.space:8080/api/im`);

// 发送消息触发滚动条滚动
const send = () => {
  if(text.value.length > 40){
    showToast('消息长度不能大于40个字符喔');
    return;
  }
  // console.log(toUser?.value?.id)
  if (client) {
    if (text.value !== '') {
      let message = {
        uid: currentUser.value.id,
        toId: toUser?.value?.id,
        text: text.value
      }
      client.send(JSON.stringify(message));
    }
  }
  text.value = ''  // 清空文本框
}

client.onopen = () => {
  console.log('open')
}
client.onclose = () => {  // 页面刷新的时候和后台websocket服务关闭的时候
  showToast('服务器断开，请刷新重试');
  console.log('close')
}

// 当收到消息
client.onmessage = (msg) => {
  console.log(msg)
  if (msg.data) {
    // console.log(msg.data)
    let json = JSON.parse(msg.data);
    // console.log(json)
    if (json.uid && json.text) {  // 聊天消息
      messages.value.push(json)
      console.log('json',json)
      console.log('messages',messages)
      // loginUserList.value.forEach(user => {
      //   if (user.id === json.uid) {
      //     user.isNew = true;
      //   }
      // })
      scrollBottom()  // 滚动页面到最底部
    }
  }
}

</script>

<style scoped>
#chat-person {
  position: absolute;
	top: 0px;
	left: 0;
  height: 90%;
  width: 100%;
  background-color: #f6f7f9;
}
.message {
  padding: 15px;
	height: 78%;
  max-height: 80%;
  overflow-y: scroll;
	overflow-x: hidden;
  background-color: #f6f7f9;
}
.chatTime {
  text-align: center;
}
.main {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}
.text {
	display: inline-block;
	padding: 0 10px;
  margin-left: 15px;
	max-width: 80%;
	background-color: #ffffff;
  line-height: 44px;
  border-radius: 8px;
}

.selfMain {
  display: flex;
  align-items: center;
  justify-content: end;
  margin-bottom: 10px;
}

.selfText {
  display: inline-block;
	padding: 0 10px;
  margin-right: 15px;
	max-width: 80%;
  line-height: 44px;
  border-radius: 8px;
  background-color:#b9e7fe;
}

.userText {
  position:absolute;
  bottom: 0;
  left: 0;
  width: 100%;
}
.submit {
  border: none;
}
</style>